package hello;
//package javax.microedition.io.file;
import javax.microedition.lcdui.Alert;
//import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
//import javax.microedition.lcdui.TextBox;
//import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import java.io.*;
import java.util.Enumeration;
import java.util.Stack;

import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;
//import javax.microedition.io.file.FileSystemRegistry;

public class TxtRemover extends MIDlet implements CommandListener {

	private Display display;
	private Splash  splash;
	private Command exit;
	private Command myCmd;
	private Command backToFormCmd;
	private Form form;
	private TextField txtField;
	private TextField lastCommand;
	private Form secondaryForm;
	private String previousPath;
	
	public TxtRemover() {
		this.display = Display.getDisplay(this);
		this.splash = new Splash("/DPY1.jpg", 0xFFFFFF);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.microedition.midlet.MIDlet#startApp()
	 */
	protected void startApp() throws MIDletStateChangeException {
		this.exit = new Command("Exit", Command.EXIT, 0x01);
		this.myCmd = new Command("Add/Remove .txt", Command.BACK, 0x01);
		this.backToFormCmd = new Command("Back to form", Command.BACK, 0x01);
		
		Displayable main = this.getMainScreen("file:///E:/testDir/");		
		this.splash.show(this.display, main, 5000);
	}

	/**
	 * Gets the application main screen.
	 * 
	 * @return main screen.
	 */
	private Displayable getMainScreen(String startPath) {
		//TODO: Implement the main screen here.
		this.form = new Form("Parent path for renaming");
		this.form.append("Path to parent txt files");
		
		this.txtField = new TextField("Path", startPath, 32, TextField.ANY);
		this.form.append(this.txtField);
		this.lastCommand = new TextField("Last traversal:", "", 256, TextField.ANY);
		this.form.append(this.lastCommand);
				
		this.form.setCommandListener(this);
		this.form.addCommand(this.exit);
		this.form.addCommand(this.myCmd);
		
		return this.form;
	}
	
	private Displayable getSecondaryScreen(String message){		
		this.secondaryForm = new Form("Changed files");
		this.AppendLine(message);		
		
		this.secondaryForm.setCommandListener(this);
		this.secondaryForm.addCommand(this.exit);
		this.secondaryForm.addCommand(this.backToFormCmd);
		
		return this.secondaryForm;
	}

	/* (non-Javadoc)
	 * @see javax.microedition.lcdui.CommandListener#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable)
	 */
	public void commandAction(Command command, Displayable displayable) {
		if (command == this.exit) {
			try {
				this.destroyApp(true);
			} catch (MIDletStateChangeException e) {
				e.printStackTrace();
			} finally {				
				this.notifyDestroyed();
			}
		}
		else if(command == this.myCmd) {
			
			String path = this.txtField.getString();
			this.previousPath = path;				

			Displayable result = this.getSecondaryScreen(path);
			
			try{
				TraverseAndRenameTxt(path);
			}
			catch(Exception e){
				Alert alert = new Alert(e.getMessage());
				display.setCurrent(alert);
			}
			
			display.setCurrent(result);	
		}
		else if(command == this.backToFormCmd){
			Displayable formScreen = this.getMainScreen(this.previousPath);
			display.setCurrent(formScreen);
		}
	}
	
	private void TraverseAndRenameTxt(String path)
	{
		try{			
				FileConnection srcconn = (FileConnection)Connector.open(path, Connector.READ_WRITE);
				
				String oldName = srcconn.getName();
				boolean isFile = false;
				String newFileName = "";
				
				if(!oldName.endsWith("/")){
					isFile = true;
					
					if(oldName.toLowerCase().endsWith(".txt")){
						int length = oldName.length();
						newFileName = oldName.substring(0, length - 4);
						srcconn.rename(newFileName);
					}
					else if(oldName.indexOf(".") < 0){
						newFileName = oldName + ".txt";
						srcconn.rename(newFileName);
					}
				}
				
		    	this.AppendLine(oldName + " --> " + newFileName);
		    	Thread.sleep(500);
		    	if(isFile){
		    		return;
		    	}
				
			    Enumeration files = srcconn.list();			    
			    
			    Stack nextFiles = new Stack();			    
			    while (files.hasMoreElements()) {
			        nextFiles.push((String) files.nextElement());
			    }
				
			    srcconn.close();
			    			    	    
			    while(!nextFiles.isEmpty()) {
			    	String file = (String) nextFiles.pop();
			        String newPath = path + file;
			        this.TraverseAndRenameTxt(newPath);			        
			    }
			}
		catch(IOException e){
			this.AppendLine("\n\r" + "Path not found: " + path + "; e.message=" + e.getMessage());		
		}
		catch(Exception e){
			this.AppendLine("\n\r" + "Some other error: " + path + "; e.message=" + e.getMessage());
		}
	}
	
	private void AppendLine(String line){
		this.secondaryForm.append(new TextField("Traversing...", line, 256, TextField.ANY));
		this.lastCommand.setString(line);
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.microedition.midlet.MIDlet#destroyApp(boolean)
	 */
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.microedition.midlet.MIDlet#pauseApp()
	 */
	protected void pauseApp() {}
}
